import uiautomator2 as u2
import cv2
import numpy as np
from PIL import Image
import io


def verify_bluetooth_status(device_id=None):
    # 方法1: 使用UI Automator2检测元素属性
    def uiautomator_method():
        try:
            d = u2.connect(device_id) if device_id else u2.connect()

            # 确保在蓝牙设置页面
            if d.app_current().get('package') != 'com.android.settings':
                d.app_start('com.android.settings', activity='.SubSettings')
                d(resourceId="com.android.settings:id/recycler_view").wait(timeout=5.0)

            # 精确XPath定位（根据图片路径）
            switch = d.xpath(
                '//*[@resource-id="com.android.settings:id/recycler_view"]'
                '/android.view.ViewGroup[1]/android.widget.LinearLayout[1]'
            ).get()

            if switch:
                return switch.info.get('checked', False)

            # 备用定位：通过文本定位相邻开关
            bluetooth_text = d(text="蓝牙")
            if bluetooth_text.exists:
                return bluetooth_text.sibling(className="android.widget.Switch").info.get('checked', False)

            return False
        except Exception as e:
            print(f"UI Automator2检测失败: {str(e)}")
            return None

    # 方法2: 使用图像识别检测开关颜色
    def image_recognition_method():
        try:
            d = u2.connect(device_id) if device_id else u2.connect()

            # 获取屏幕截图
            screenshot = d.screenshot(format='pillow')

            # 根据图片中的位置坐标裁剪开关区域
            # 坐标信息: {"x":868,"y":455,"width":135,"height":89}
            left, top, width, height = 868, 455, 135, 89
            switch_area = screenshot.crop((left, top, left + width, top + height))

            # 转换OpenCV格式
            opencv_img = cv2.cvtColor(np.array(switch_area), cv2.COLOR_RGB2BGR)

            # 将图像转换为HSV颜色空间
            hsv = cv2.cvtColor(opencv_img, cv2.COLOR_BGR2HSV)

            # 定义蓝色范围 (HSV格式)
            lower_blue = np.array([100, 150, 50])
            upper_blue = np.array([130, 255, 255])

            # 创建蓝色掩膜
            mask = cv2.inRange(hsv, lower_blue, upper_blue)

            # 计算蓝色像素比例
            blue_pixels = cv2.countNonZero(mask)
            total_pixels = mask.size
            blue_ratio = blue_pixels / total_pixels

            return blue_ratio > 0.15  # 如果蓝色像素超过15%，则认为开关开启
        except Exception as e:
            print(f"图像识别失败: {str(e)}")
            return None

    # 主验证逻辑
    print("=" * 50)
    print("开始验证蓝牙开关状态...")

    # 优先使用UI Automator方法
    # uia_result = uiautomator_method()
    #
    # if uia_result is not None:
    #     status = "开启" if uia_result else "关闭"
    #     print(f"✅ UI Automator检测完成: 蓝牙状态为【{status}】(checked={uia_result})")
    #     return uia_result
    #
    # print("⚠️ UI Automator检测失败，尝试图像识别...")

    # 图像识别作为备选方案
    img_result = image_recognition_method()

    if img_result is not None:
        status = "开启" if img_result else "关闭"
        print(f"🖼️ 图像识别完成: 蓝牙状态为【{status}】(蓝色像素检测)")
        return img_result

    print("❌ 所有方法均失败，无法验证蓝牙状态")
    return False


# 使用示例
if verify_bluetooth_status():
    print("最终结果: 蓝牙已开启")
else:
    print("最终结果: 蓝牙未开启")